I am trying to convert unicode[marathi] string in to byte array,but when I convert it and print, it shows " ? ? ? ? ? ? " like this.
using System;
using System.Text;
public class Example
{
public static void Main()
{
// Input string.
const string input = "पांडुरंग";
// Invoke GetBytes method.
// ... You can store this array as a field!
byte[] array = Encoding.ASCII.GetBytes(input);
// Loop through contents of the array.
foreach (byte element in array)
{
Console.WriteLine("{0} = {1}", element, (char)element);
}
Console.ReadLine();
}
}
.
Output:
63 = ?
63 = ?
63 = ?
63 = ?
63 = ?
63 = ?
63 = ?
63 = ?
if anyone have idea about this please help us.thanks in advance.
Try using Encoding.Unicode instead of Encoding.ASCII:
byte[] array = Encoding.Unicode.GetBytes(input);
Also, you are converting each byte to a separate char, whereas actually each character is represented by two bytes. The easiest way to get the chars from the byte array is to convert the bytes back to string using the same encoding, and calling GetCharArray() on the rsulting string:
foreach (byte element in Encoding.Unicode.GetString(array).ToCharArray()
{
Console.WriteLine("{0} = {1}", element, (char)element);
}
Related
When I use tools such as snmp-walk or snmp-get to query an OID with a return type of MacAddress, It'll always parse the data as a HexString and display it properly. Even when they don't have the MIBs loaded it'll still works.
bash#snmpwalk -v 2c -c public 10.1.2.3 1.3.6.1.4.1.14179.2.2.1.1
SNMPv2-SMI::enterprises.14179.2.2.1.1.1.16.189.24.206.212.64 = Hex-STRING: 10 BD 18 CE D4 40
SNMPv2-SMI::enterprises.14179.2.2.1.1.1.100.233.80.151.114.192 = Hex-STRING: 64 E9 50 97 72 C0
However, I can't seem to get the same result from Lextm.SharpSnmpLib (11.2.0). Data types of MacAddress don't get decoded correctly and it's a manual process to convert it to a proper MAC.
public void WalkTable()
{
const string baseOid = "1.3.6.1.4.1.14179.2.2.1.1"; //The entire table
const string community = "public";
var ep = new IPEndPoint(IPAddress.Parse("10.1.2.3"), 161);
var results = new List<Variable>();
Messenger.Walk(VersionCode.V2, ep, new OctetString(community), new ObjectIdentifier(baseOid), results, 60000, WalkMode.WithinSubtree);
foreach(var v in results)
Console.WriteLine(v.Data.ToString());
}
Am I doing something wrong or is this just how the library works?
You are outputting the MAC Address as ASCII instead of Hex. Here's a quick method I put together that will detect non-ascii characters and output as hex if any are found.
public void WalkTable()
{
const string baseOid = "1.3.6.1.4.1.14179.2.2.1.1"; //The entire table
const string community = "public";
var ep = new IPEndPoint(IPAddress.Parse("10.1.2.3"), 161);
var results = new List<Variable>();
Messenger.Walk(VersionCode.V2, ep, new OctetString(community), new ObjectIdentifier(baseOid), results, 60000, WalkMode.WithinSubtree);
foreach(var v in results)
//If the result is an OctetString, check for ascii, otherwise use ToString()
Console.WriteLine(v.Data.TypeCode.ToString()=="OctetString" ? DecodeOctetString(v.Data.ToBytes()) : v.Data.ToString())
}
}
public string DecodeOctetString(byte[] raw)
{
//First 2 bytes are the Type, so remove them
byte[] bytes = new byte[raw.Length - 2];
Array.Copy(raw, 2, bytes, 0, bytes.Length);
//Check if there are any non-ascii characters
bool ascii = true;
foreach (char c in Encoding.UTF8.GetString(bytes))
{
if (c >= 128)
{
ascii = false;
}
}
//If it's all ascii, return as ascii, else convert to hex
return ascii ? Encoding.ASCII.GetString(bytes) : BitConverter.ToString(bytes);
}
I have written a piece of code to get a value from a currency converter like below:
WebClient n = new WebClient();
var JsonData = n.DownloadString("http://currencyconverterapi.com/api/v6/convert?q=USD_NRI&compact=ultra&apiKey=");
JsonData = {"USD_INR":69.657026} // Got value result from JsonData
dynamic JObj = JObject.Parse(JsonData);
dynamic JOresult = JObject.Parse(Convert.ToString(JObj.USD_INR)); //Got Error here (Error reading JObject from JsonReader. Current JsonReader item is not an object: Float. Path '', line 1, position 9.)
string JOFilter_Val = Convert.ToString(JOresult.val);
decimal Total = 230 * Convert.ToDecimal(JOFilter_Val);
return Total;
I want to get the value '69.657026' from multiplying with the decimal 230, and return the final result. Can anybody tell me what I'm doing wrong and if possible please correct it?
It's not really clear why you're trying to parse 69.657026 as a JObject - it's not an object.
I suspect you don't need to do that at all - just use JObj.USD_INR as a decimal:
decimal value = JObj.USD_INR; // Use the dynamic conversion to handle this
In general you seem to be converting back and forth far more than you need to. Here's a complete example of what I think you're trying to do:
using Newtonsoft.Json.Linq;
using System;
class Test
{
static void Main()
{
string json = "{ \"USD_INR\": 69.657026 }";
dynamic obj = JObject.Parse(json);
decimal rate = obj.USD_INR;
decimal total = 230 * rate;
Console.WriteLine(total); // 16021.115980
}
}
Alternatively, without dynamic typing:
using Newtonsoft.Json.Linq;
using System;
class Test
{
static void Main()
{
string json = "{ \"USD_INR\": 69.657026 }";
JObject obj = JObject.Parse(json);
decimal rate = (decimal) obj["USD_INR"];
decimal total = 230 * rate;
Console.WriteLine(total);
}
}
Sometimes from network transmissions/usdb devices you receive the data has a hexadimal string eg:
"12ADFF1345"
These type of string I want somehow to be converted into a binary equivalent into a buffer, in order to perform a some mathematical or binary operations on them.
Do you know how I can achieve that?
Use the builtin Buffer class :
let buf1 = Buffer.from('12ADFF1345', 'hex');
let value = buf1.readInt32LE(0);
let value2 = buf1.readInt16LE(2);
console.log(value,value2);
>> 335523090 5119
// '13ffad12' '13FF' (LE)
>> 313392915 -237
// '12ADFF13' 'ff13' (BE)
https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding
Yes I know how to do that, the algorithm is simple (assuming that you have no escape characters):
Split the read string into a character.
Group each character pair.
Then generate the string 0x^first_character_pair^
parseInt the string above with base 16
In other words consult the following code:
const hexStringToBinaryBuffer = (string) => {
const subStrings = Array.from(string);
let previous = null;
const bytes = [];
_.each(subStrings, (val) => {
if (previous === null) { // Converting every 2 chars as binary data
previous = val;
} else {
const value = parseInt(`0x${previous}${val}`, 16);
bytes.push(value);
previous = null;
}
});
return Buffer.from(bytes);
};
This is usefull if you pass as string the result of a Buffer.toString('hex') or equivalent method via a network socket or a usb port and the other end received it.
I have string value like this:
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
I just need to retrieve role to string array. I wonder if there is the best way to split the string in C# 4.0
string[] arrStrRole = strRole.Split('|').Select .. ??
Basically, I need brandUK, brandUsa, brandAu to string[] arrStrRole.
Thanks.
string[] arrStrRole = strRole.Split('|').Select(r => r.Split(new []{"role="}, StringSplitOptions.None)[1]).ToArray()
results in an string array with three strings:
branduk
brankdusa
brandAu
you can use string[] arrStrRole = strRole.Split('|',','); and this will split according to | and , characters
You can use String.Split in this LINQ query:
var roles = from token in strRole.Split('|')
from part in token.Split(',')
where part.Split('=')[0] == "role"
select part.Split('=')[1];
Note that this is yet prone to error and requires the data always to have this format. I mention it because you've started with Split('|').Select.... You can also use nested loops.
If you need it as String[] you just need to call ToArray:
String[] result = roles.ToArray();
I would go with Regex rather than splitting string. In combination with your intended Select solution, it could look like this:
var roles = Regex.Matches(strRole, #"role=(\w+)")
.Cast<Match>()
.Select(x => x.Groups[1].Value).ToArray();
You could use an extension like this which would allow you to test it easily.
public static string[] ParseRolesIntoList(this string csvGiven)
{
var list = new List<string>();
if (csvGiven == null) return null;
var csv = csvGiven.Split(',');
foreach (var s in csv)
{
if (string.IsNullOrEmpty(s)) continue;
if(!s.StartsWith("role")) continue;
var upperBound = s.IndexOf("|");
if (upperBound <= 0) upperBound = s.Length;
var role = s.Substring(s.IndexOf("=") + 1,
upperBound - s.IndexOf("=") - 1);
list.Add(role);
}
return list.ToArray();
}
Test below found brankdusa typo in your example. Some of the other answers would not deal with brandAu as it matches slightly differently. Try running this test against them if you like
[Test]
public void Should_parse_into_roles()
{
//GIVEN
const string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
//WHEN
var roles = strRole.ParseRolesIntoList();
//THEN
Assert.That(roles.Length, Is.EqualTo(3));
Assert.That(roles[0], Is.EqualTo("branduk"));
Assert.That(roles[1], Is.EqualTo("brankdusa"));
Assert.That(roles[2], Is.EqualTo("brandAu"));
}
This gives an array of the 3 values.
void Main()
{
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
var arrStrRole = strRole.Split('|',',')
.Where(a => a.Split('=')[0] == "role")
.Select(b => b.Split('=')[1]);
arrStrRole.Dump();
}
is it possible or is there any overload to get a less than 32 characters of GUID ?
currently i am using this statement but its giving me error
string guid = new Guid("{dddd-dddd-dddd-dddd}").ToString();
i want a key of 20 characters
You can use a ShortGuid. Here is an example of an implementation.
It's nice to use ShortGuids in URLs or other places visible to an end user.
The following code:
Guid guid = Guid.NewGuid();
ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid
Console.WriteLine( sguid1 );
Console.WriteLine( sguid1.Guid );
Will give you this output:
FEx1sZbSD0ugmgMAF_RGHw
b1754c14-d296-4b0f-a09a-030017f4461f
This is the code for an Encode and Decode method:
public static string Encode(Guid guid)
{
string encoded = Convert.ToBase64String(guid.ToByteArray());
encoded = encoded
.Replace("/", "_")
.Replace("+", "-");
return encoded.Substring(0, 22);
}
public static Guid Decode(string value)
{
value = value
.Replace("_", "/")
.Replace("-", "+");
byte[] buffer = Convert.FromBase64String(value + "==");
return new Guid(buffer);
}
Use Jeff Attwood's ASCII85...
http://www.codinghorror.com/blog/2005/10/equipping-our-ascii-armor.html
and
http://www.codinghorror.com/blog/2005/10/c-implementation-of-ascii85.html